package com.hancai.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hancai.constant.Constants;
import com.hancai.manager.RedisManager;
import com.hancai.mapper.TRoleMapper;
import com.hancai.mapper.TUserMapper;
import com.hancai.model.TActivityRemark;
import com.hancai.model.TRole;
import com.hancai.model.TUser;
import com.hancai.query.BaseQuery;
import com.hancai.query.UserQuery;
import com.hancai.service.UserService;
import com.hancai.util.CacheUtils;
import com.hancai.util.JWTUtils;
import jakarta.annotation.Resource;
import org.apache.naming.factory.BeanFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestHeader;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 涵菜
 * @version 1.0
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private TUserMapper userMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private TRoleMapper tRoleMapper;

    @Resource
    private RedisManager redisManager;

    /**
     * 登录查询
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser tUser=userMapper.selectByLoginAct(username);
        if(tUser==null){
            throw new UsernameNotFoundException("登录账号不存在");
        }
        //查询一下当前用户的角色
        List<TRole>tRoleList=tRoleMapper.selectByUserId(tUser.getId());
        //字符串的角色列表
        List<String>stringRoleList=new ArrayList<>();
        tRoleList.forEach(tRole -> {
            stringRoleList.add(tRole.getRole());
        });
        tUser.setRoleList(stringRoleList);
        return tUser;
    }

    @Override
    public PageInfo<TUser> getUserByPage(Integer current) {
        //设置PageHelper
        PageHelper.startPage(current, Constants.PAGE_SIZE);
        //查询
        List<TUser>list=userMapper.selectUserByPage(BaseQuery.builder().build());
        //封装分页数据到PageInfo
        PageInfo<TUser>info=new PageInfo<>(list);
        return info;
    }

    @Override
    public TUser getUserById(Integer id) {
        return userMapper.selectDetailById(id);
    }

    @Override
    public int saveUser(UserQuery userQuery) {
        TUser tUser=new TUser();
        //把userQuery对象的属性数据复制到user对象(复制要求：两个类的字段名和类型相同)
        BeanUtils.copyProperties(userQuery,tUser);
        tUser.setLoginPwd(passwordEncoder.encode(userQuery.getLoginPwd()));
        tUser.setCreateTime(new Date());//当前时间
        Integer loginUserId= JWTUtils.parseUserFromJWT(userQuery.getToken()).getId();
        tUser.setCreateBy(loginUserId);
        return userMapper.insertSelective(tUser);
    }

    @Override
    public int updateUser(UserQuery userQuery) {
        TUser tUser=new TUser();
        //把userQuery对象的属性数据复制到user对象(复制要求：两个类的字段名和类型相同)
        BeanUtils.copyProperties(userQuery,tUser);
        if(StringUtils.hasText(userQuery.getLoginPwd())){//如果有密码的话
            tUser.setLoginPwd(passwordEncoder.encode(userQuery.getLoginPwd()));
        }
        tUser.setEditTime(new Date());//编辑时间
        Integer loginUserId= JWTUtils.parseUserFromJWT(userQuery.getToken()).getId();
        tUser.setEditBy(loginUserId);
        return userMapper.updateByPrimaryKeySelective(tUser);
    }

    @Override
    public int delUserById(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int batchDelUserIds(List<String> idList) {
        return userMapper.deleteByIds(idList);
    }

    //三个方法分别作为方法形参
    @Override
    public List<TUser> getOwnerList() {
        //1，从redis中查询-缓存
        //2，redis查不到，就从数据库查询，并且把数据放入redis(5分钟过期)
        return CacheUtils.getCacheData(()->{
            //生产，从redis中查询数据
            return (List<TUser>)redisManager.getValue(Constants.REDIS_OWNER_KEY);
        },()->{
           //生产，从mysql中查询数据
            return userMapper.selectByOwner();
        },(t)->{
            //消费，把数据放入缓存redis
            redisManager.setValue(Constants.REDIS_OWNER_KEY,t);
        });
    }
}
